package com.js.blog.util;


import com.auth0.jwt.JWT;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.util.Arrays;
import java.util.Date;

/**
 * @author yanglin
 * @create 2024-02-29 16:15 星期四
 * description:   利用JWT进行加解密操作
 */
public class JwtAuthentication {
    
    //密钥
    private static final String SECRET_KEY = Arrays.toString(Keys.secretKeyFor(SignatureAlgorithm.HS256).getEncoded());
    
    //利用用户id生成 JWT Token
    public static String generateToken(Long id){
        
        //设置Token签发时间
        Date date = new Date();
        
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET_KEY);
        SecretKeySpec signingKey = new SecretKeySpec(apiKeySecretBytes, SignatureAlgorithm.HS256.getJcaName());

        //创建JWT构建器
        return Jwts.builder()
                .setSubject(id.toString())
                .setIssuedAt(date)
                .signWith(signingKey,SignatureAlgorithm.HS256)
                .compact();
        
    }
    
    
    //解析JWT Token
    public static String validateToken(String token){
        try {
            String userId = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(SECRET_KEY))
                    .parseClaimsJws(token)
                    .getBody()
                    .getSubject();
            return userId;
        }catch (Exception e){
            return null;
        }
    }
}
